<template>
  <div>
    <text-input title="电话" v-model="phoneNum" :required="true" type="number"></text-input>
    <text-input title="价格" unit="万元" v-model="price" type="number" placeholder="面议" :max="10"></text-input>

    <div class="form-row flex-row">
      <span class="title required">上牌时间：</span>
      <div class="date flex-row flex-grow flex-between" @click="openDateSelect">
        <div class="year">{{ date.split('-')[0] }} 年</div>
        <div class="month">{{ date.split('-')[1] }} 月</div>
        <div class="day">{{ date.split('-')[2] }} 日</div>
      </div>
    </div>
    
    <text-input title="车辆品牌" :value="showingManufText" :required="true" :readonly="true"
      placeholder="请选择"
      @click.native="openMaunfSelect"
    ></text-input>
    
    <text-input title="所属公司" :value="company"></text-input>

    <div class="form-row flex-row">
      <span class="title">过&emsp;&emsp;户：</span>
      <checker v-model="transfer" :items="[
        { '包过户': 1 },
        { '不包过户': 0 }
      ]"></checker>
    </div>

    <text-input title="备注" v-model="remark"></text-input>

    <div class="form-row flex-row" style="height:initial;">
      <span class="title required">车辆图片：</span>
      <div class="imgs" ref="imgs">
        <div class="imgs-container" style="width:max-content;" ref="imgsContainer">
          <img v-for="(url, index) in imgs" :key="index" :src="url"
            @click="$deepToView('picViewer', { params: { url } })" class="uploadedImg"
          >
          <label>
            <input type="file" accept="image/*" style="position:fixed; left: -9999px;" @change="imgUploadReady">
            <img class="addImgBtn" :src="require('@img/btn/release_img_addpictures@2x.png')">
          </label>
        </div>
      </div>
    </div>

    <div class="theme-btn submitBtn" :class="{ disabled }" @click="submit">我要发布</div>

    <popup-picker v-model="manuf" title="_" :data="showingManufList" class="hidePicker" ref="picker"
      :columns="2"
    ></popup-picker>
  </div>
</template>

<script>
import { Picker, PopupPicker } from 'vux'
import TextInput from '@c/form/TextInput'
import Checker from '@c/form/Checker'
import upload from '@u/upload.js'
import test from '@u/test.js'

function getTodayDateStr(){
  var date = new Date()
  var foo = val => val < 10 ? '0' + val : val
  var today = [date.getFullYear(), foo(date.getMonth() + 1), foo(date.getDate())]
  return today.join('-')
}

export default {
  components: {
    Checker,
    TextInput,
    PopupPicker
  },
  
  data (){
    return {
      phoneNum: this.$store.state.user.data.phonenum || '',   // 手机号码
      price: '',    // 价格
      date: getTodayDateStr(),    // 上牌时间
      manuf: [],    // [0]：品牌，[1]：系列
      company: '',  // 公司
      remark: '',   // 备注
      transfer: 1,  // 包过户
      imgs: [],   // 已上传图片
      disabled: true,   // 发布按钮是否可点击
      loopCheckerKey: 0,     // 声明一个setInterval，循环检测各字段是否正确，以改变提交按钮状态 

      manufList: null,    // 品牌数据
      seriesList: {}      // 系列数据
    }
  },

  beforeRouteLeave (to, from, next){
    // 离开页面清除字段确认器
    clearInterval(this.loopCheckerKey)
    next()
  },

  activated (){
    // 激活页面时开始每200毫秒确认一次各字段，正确将点亮按钮
    this.loopCheckerKey = setInterval(() => this.disabled = !this.testInput(false), 200)
  },

  mounted (){
    // 请求厂商和对应系列数据
    _api('carManuf/getListByCon', { is_paginate: 0 })
    .then(data =>{
      this.manufList = data
      data.forEach(val =>{
        _api('carSeries/getListByCon', { car_manuf_id: val.id, is_paginate: 0 })
        .then(data => this.$set(this.seriesList, val.id, data))
      })
    })
  },

  computed: {
    // 显示的厂商文字
    showingManufText (){
      if(!this.manufList || !this.manuf.length) return ''
      var manuf = this.manufList.filter(val => val.id.toString() === this.manuf[0])[0].name
      var serice = this.seriesList[this.manuf[0]].filter(val =>
        val.id.toString() === this.manuf[1].replace(/^\$/, '')
      )[0].name
      return manuf + ' ' + serice
    },

    // manuf的picker需要的数据
    showingManufList (){
      if(this.manufList && Object.keys(this.seriesList).length === this.manufList.length){
        var data = []
        this.manufList.forEach(val =>{
          data.push({ name: val.name, value: val.id.toString() })
          this.seriesList[val.id].forEach(serice => 
            // 加$避免厂商和型号id有重复的情况（vux的picker依靠id进行父子选择列的划分）
            data.push({ name: serice.name, value: '$' + serice.id, parent: val.id.toString() })
          )
        })

        return data
      }else return []
    }
  },

  methods: {
    // 开启日期选择器
    openDateSelect (){
      this.$vux.datetime.show({
        confirmText: '确认',
        cancelText: '取消',
        onConfirm: val => this.date = val
      })
    },

    // 开启品牌选择器
    openMaunfSelect (){
      this.$refs.picker.$el.querySelector('.weui-label').click()
    },

    // input标签图片ready事件
    imgUploadReady (e){
      var img = e.target.files[0]
      this.$vux.loading.show()
      if(this.imgs.length > 8){
        this.$alert.toast('最多上传九张图片')
        return
      }
      upload(img)
      .then(imgUrl => {
        var img = new Image()
        img.src = imgUrl
        img.onload = () =>{
          this.imgs.push(imgUrl)
          this.$vux.loading.hide()
          this.$nextTick(() => this.$refs.imgs.scrollTo(this.$refs.imgsContainer.offsetWidth, 0)) 
        }
      })
      .catch(e =>{
        console.log(e)
        this.$vux.loading.hide()
        this.$alert.toast('上传失败，请重试')
      })
    },

    // 确认各字段
    testInput (toast = true){
      if(!this.phoneNum.length){
        toast && this.$alert.toast('电话/手机号码不能为空')
        return false
      }
      if(!test.phoneNum(this.phoneNum)){
        toast && this.$alert.toast('请输入正确的电话/手机号码')
        return false
      }
      if(this.price && !test.price(this.price)){
        toast && this.$alert.toast('请输入正确的价格')
        return false
      }
      if(!this.manuf.length){
        toast && this.$alert.toast('车辆品牌不能为空')
        return false
      }

      // if(!this.imgs.length){
      //   toast && this.$alert.toast('请至少上传一张图片')
      //   return false
      // }

      return true
    },

    // 提交
    submit (){
      if(this.testInput()){
        var request =  {
          car_manuf_id: this.manuf[0],
          car_series_id: this.manuf[1].replace(/^\$/, ''),
          tel: this.phoneNum,
          license_at: this.date,
          company: this.company,
          price: this.price || 0,
          transfer: this.transfer,
          remark: this.remark
        }

        if(this.imgs.length) request.img = this.imgs.join(',')

        _api('usedCar/publish', request).then(data =>{
          this.$alert.alert('发布成功')
          this.$router.replace({
            name: 'index/home',
            query: { reload: true }
          })
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@sty/publish.less';

.hidePicker{
  position: fixed !important;
  left: -9999px;
}
</style>